package com.weiweiqin.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class XssFilter implements Filter {
    FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void destroy() {
        this.filterConfig = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
    	HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
    	try{
    		String currentURL = req.getRequestURI();
    		String targetURL = currentURL.substring(currentURL.indexOf("/", 1));
    		currentURL.length();
    		if (!isFreePage(targetURL)) {
    			chain.doFilter(new XssHttpServletRequestWrapper(
    	                (HttpServletRequest) request), response);
    		}else{
    			chain.doFilter(req, res);
    		}
    		
    	}catch(Exception e){
    		chain.doFilter(req, res);
    	}
    }
    
    private boolean isFreePage(String targetURL){
		String freeURLs = filterConfig.getInitParameter("freeURL");
		freeURLs = freeURLs.replaceAll("\n","");
		freeURLs = freeURLs.replaceAll("\t","");
		String[] split = freeURLs.split(";");
		if(split.length !=0){
			for (String freeURL : split) {
				if(freeURL.indexOf(targetURL) != -1){
					return true;
				}
			}
		}
		return false;
		
	}
}